<template>
    <div class="screen" id="screen">
        <div class="wrapper">
            <div class="bu" @click="changeStatus(index)" style="margin-left: 10px;" v-for="(item, index) in status"
                :key="index" :id="item.id" :class="currentIndex == index ? 'active' : ''">{{ item.name }}</div>
        </div>
        <el-dialog v-model="centerDialogVisible" title="Warning" width="800" align-center>
            <img :src="imgurl" alt="" width="700" height="500">
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="centerDialogVisible = false">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue'
import * as THREE from 'three';
import ZThree from '../zthree/three';
import { Capsule } from 'three/examples/jsm/math/Capsule.js';
import { loadModel } from '../zthree/loadModel'
import { bigData } from '../assets/bigData'
var app = null;
var scene = null;//场景
var camera = null;//相机
var renderer = null;//渲染器
var imgurl = ref()
const centerDialogVisible = ref(false)
var currentIndex = ref(0)
var status = ref([{
    id: 'Idle',
    name: '空闲'
},
{
    id: 'Run',
    name: '跑步'
},
{
    id: 'Walk',
    name: '行走'
}
])
const changeStatus = (index) => {
    currentIndex.value = index
    // if (app.playMixer) {
    //     app.playMixer.stopAllAction()
    //     app.playMixer.setAnimation(status[index].id)
    // }
}
const keyStates = {
    // 使用W、A、S、D按键来控制前、后、左、右运动
    // false表示没有按下，true表示按下状态
    W: false,
    A: false,
    S: false,
    D: false,
};
// 当某个键盘按下设置对应属性设置为true
document.addEventListener('keydown', (event) => {
    if (event.code === 'KeyW') keyStates.W = true;
    if (event.code === 'KeyA') keyStates.A = true;
    if (event.code === 'KeyS') keyStates.S = true;
    if (event.code === 'KeyD') keyStates.D = true;
});
// 当某个键盘抬起设置对应属性设置为false
document.addEventListener('keyup', (event) => {
    if (event.code === 'KeyW') keyStates.W = false;
    if (event.code === 'KeyA') keyStates.A = false;
    if (event.code === 'KeyS') keyStates.S = false;
    if (event.code === 'KeyD') keyStates.D = false;
});
const playerCollider = new Capsule(//胶囊体
        new THREE.Vector3(0, 0.36, 0), // 胶囊体起点
        new THREE.Vector3(0, 1, 0),    // 胶囊体终点
        0.35                           // 胶囊体半径
);
console.log('playerCollider',playerCollider);

const v = new THREE.Vector3(0, 0, 0);
const vMax = 5;//限制玩家角色最大速度
const damping = -0.04;//阻尼 当没有WASD加速的时候，人、车等玩家角色慢慢减速停下来
const a = 12;//加速度：调节按键加速快慢
const zthree = async () => {
    app = new ZThree('screen')
    window.app = app
    app.initThree()
    // app.initOrbitControls()
    app.initAxesHelper()
    app.initRaycaster(mouseClick)
    app.initLight()
    app.initSky()
    scene = app.scene
    console.log(scene);
    camera = app.camera
    camera.position.set(0, 3, -6)
    camera.lookAt(0, 1.7, 0)
    renderer = app.renderer
    // const geometry = new THREE.BoxGeometry(1, 1, 1);
    // const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    // const cube = new THREE.Mesh(geometry, material);
    // console.log(cube);

    // scene.add(cube);
    await loadModel(app)
    var clock = new THREE.Clock();
    app.animate(() => {
        const deltaTime = clock.getDelta();
        if (v.length() < vMax) {//限制最高速度
            if (keyStates.W) {
                if (currentIndex.value == 0) {

                } else {
                    const front = new THREE.Vector3();//先假设W键对应运动方向为z
                    app.model2.getWorldDirection(front);
                    v.add(front.multiplyScalar(a * deltaTime));
                }

            }
            if (keyStates.S) {
                if (currentIndex.value == 0) {

                } else {
                    // 与W按键相反方向
                    const front = new THREE.Vector3();
                    app.model2.getWorldDirection(front);
                    v.add(front.multiplyScalar(-a * deltaTime));
                }
            }
            if (keyStates.A) {//向左运动
                if (currentIndex.value == 0) {

                } else {
                    const front = new THREE.Vector3();
                    app.model2.getWorldDirection(front);
                    const up = new THREE.Vector3(0, 1, 0);//y方向

                    const left = up.clone().cross(front);
                    v.add(left.multiplyScalar(a * deltaTime));
                }

            }
            if (keyStates.D) {//向右运动
                if (currentIndex.value == 0) {

                } else {
                    const front = new THREE.Vector3();
                    app.model2.getWorldDirection(front);
                    const up = new THREE.Vector3(0, 1, 0);//y方向
                    //叉乘获得垂直于向量up和front的向量 左右与叉乘顺序有关,可以用右手螺旋定则判断，也可以代码测试结合3D场景观察验证
                    const right = front.clone().cross(up);
                    v.add(right.multiplyScalar(a * deltaTime));
                }

            }
        }
        // 阻尼减速
        v.addScaledVector(v, damping);

        //更新玩家角色的位置  当v是0的时候，位置更新也不会变化
        const deltaPos = v.clone().multiplyScalar(deltaTime);
        setTimeout(() => {
            app.model2.position.add(deltaPos);
            //把胶囊体和人物模型进行绑定
            // 更新人物模型的位置
            playerCollider.start.copy(app.model2.position);
            playerCollider.end.copy(app.model2.position).add(new THREE.Vector3(0, 0.65, 0));
            var collisions =  app.worldOctree.capsuleIntersect(playerCollider)
            console.log('collisions',collisions);
            if(collisions){
                // 处理碰撞
                const collisionNormal = collisions.normal.clone().normalize();
                const overlap = playerCollider.radius - collisions.depth;
                playerCollider.translate(collisionNormal.multiplyScalar(overlap));
                app.model2.position.copy(playerCollider.start)
            }
            
        }, 500)


        if (app.playMixer) {
            app.playMixer.update(deltaTime)
        }
        renderer.render(scene, camera)
    })

}

function mouseClick(selectObj) {
    if (selectObj?.object?.name.indexOf('展览位屏幕') > -1) {
        let model = selectObj.object
        let obj = bigData[model.name]
        console.log('obj', obj);
        imgurl.value = obj.url
        centerDialogVisible.value = true
    }
}

onMounted(() => {
    zthree()
    let viewBool = true;//true表示第三人称，false表示第一人称
    document.addEventListener('keydown', (event) => {
        if (event.code === 'KeyV') {
            if (viewBool) {
                // 切换到第一人称
                camera.position.z = 1;//相机在人前面一点 看不到人模型即可
            } else {
                // 切换到第三人称
                camera.position.z = -5;//相机在人后面一点
            }
            viewBool = !viewBool;
        }
    });
})

</script>
<style scoped>
#screen {
    width: 100vw;
    height: 100vh;
}

.wrapper {
    position: absolute;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
}

.bu {
    display: inline-block;
    width: 200px;
    height: 40px;
    line-height: 40px;
    border-radius: 20px;
    color: #fff;
    text-align: center;
}

.active {
    background-color: #409eff;
}
</style>